package selectdemo

import (
	"fmt"
	"math/rand"
	"time"
)

func StringWorker() chan string {
	worker := make(chan string)
	go func(worker chan string) {
		for s := range worker {
			//调整收发速度使用
			time.Sleep(2 * time.Second)
			fmt.Printf("woker receive %s\n", s)
		}
	}(worker)
	return worker
}

//边收边发
/*func SelectDemo(){
	c1, c2 := generator(1), generator(2)
	worker := StringWorker()
	var n string
	for {
		select {
		case n = <-c1:
			worker<-n
		case n = <-c2:
			worker<-n
		}

	}
}
*/

func SeclectDemo() {
	//var c1, c2 chan int //nil
	//两个channel发送数据
	c1, c2 := generator(1), generator(2)
	worker := StringWorker()
	hasValue := false
	var n string
	for {
		var activeChan chan string
		if hasValue {
			activeChan = worker
		}
		select {
		case n = <-c1:
			hasValue = true
		case n = <-c2:
			hasValue = true
		case activeChan <- n:
			hasValue = false
		}

	}
}

func generator(id int) chan string {
	out := make(chan string)
	go func(out chan string) {
		i := 0
		for {
			time.Sleep(time.Duration(rand.Intn(1500)) * time.Millisecond)
			out <- fmt.Sprintf("%d号channel放入号码%d", id, i)
			i++
		}
	}(out)
	return out
}

//速度不均匀
/*
func SeclectDemo() {
	//var c1, c2 chan int //nil
	//两个channel发送数据
	c1, c2 := generator(1), generator(2)
	worker := StringWorker()
	//hasValue := false
	//var n string
	var values []string

	for {
		var activeChan chan string
		var activeValue string
		if len(values)>0{
			activeChan = worker
			activeValue = values[0]
		}
		select {
		case n := <-c1:
			//hasValue = true
			values = append(values,n)
		case n := <-c2:
			values = append(values,n)
		case activeChan<-activeValue:
			values = values[1:]
			fmt.Printf("此时积压了%d个数据\n",len(values))
			fmt.Println(values)
		}
	}
}

*/

// 定时退出
/*
func SeclectDemo() {
	//var c1, c2 chan int //nil
	//两个channel发送数据
	c1, c2 := generator(1), generator(2)
	worker := StringWorker()
	//hasValue := false
	//var n string
	var values []string

	tm := time.After(10 * time.Second)
	tick := time.Tick(3 * time.Second)

	for {
		var activeChan chan string
		var activeValue string
		if len(values) > 0 {
			activeChan = worker
			activeValue = values[0]
		}
		select {
		case n := <-c1:
			//hasValue = true
			values = append(values, n)
		case n := <-c2:
			values = append(values, n)
		case activeChan <- activeValue:
			values = values[1:]
		case <-time.After(800 * time.Millisecond):
			fmt.Println("timeout")
		case <-tick:
			fmt.Printf("此时积压了%d个数据\n", len(values))
			fmt.Println(values)
		case <-tm:
			fmt.Println("10秒已到,退出")
			return
		}
	}
}
*/
